package hasthi.container.p2p;

import hasthi.common.HasthiException;
import hasthi.container.AbstractMessageContext;
import hasthi.container.NodeAddress;

import java.io.IOException;
import java.io.OutputStream;

import javax.xml.namespace.QName;

import org.apache.xmlbeans.XmlObject;

public class P2PMessageContext extends AbstractMessageContext{
    private XmlMesssage envelope;
   
    public P2PMessageContext(XmlMesssage envelope,NodeAddress toAddress) throws HasthiException{
        super(toAddress);
        processEnvelope(envelope);
    }
    
    public P2PMessageContext(XmlObject bodyContent,NodeAddress toAddress) throws HasthiException{
        super(toAddress);
        processEnvelope(envelope);
    }
    

    private void processEnvelope(XmlMesssage envelope) throws HasthiException {
        this.envelope = envelope;
        this.soapAction = envelope.getAction();
        this.request = envelope.getBodyContent();
    }
    
    public Object getHeader(QName name) {
        return envelope != null? envelope.getHeader(name):null;
    }

    public void writeTo(OutputStream outStream) throws IOException {
        envelope = new UnicastXmlMessage(request,address.getAddressAsObject(),soapAction);
        envelope.getEnvelope().save(outStream);
    }

    public XmlMesssage getEnvelope() {
        return envelope;
    }

}
